//
//  YYTextView.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/13.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import UIKit

class YYTextView: UITextView {
    //重写 font 属性,当外界设置字体大小的时候,更改占位文字的大小
    override var font: UIFont? {
        didSet{
            placeholderLabel.font = font
        }
    }
    
    //供外界设置占位文字的属性
    var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addSubview(placeholderLabel)
        //监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    //监听方法
    @objc private func textViewDidChanged(){
        placeholderLabel.hidden = self.hasText()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        
        placeholderLabel.frame.size = (placeholderLabel.text! as NSString).boundingRectWithSize(CGSize(width: self.frame.size.width - placeholderLabel.frame.origin.x, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: placeholderLabel.font], context: nil).size
    }

    //Mark-懒加载
    private lazy var placeholderLabel: UILabel = {
        let placeHolder = UILabel()
        placeHolder.text = "大声告诉我,你想要发表什么样的微博"
        placeHolder.font = UIFont.systemFontOfSize(14)
        placeHolder.textColor = UIColor.lightGrayColor()
        placeHolder.numberOfLines = 0
        return placeHolder
    }()

    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
